package com.ddfeiyu.agreement.codec;


import com.ddfeiyu.agreement.Packet;
import com.ddfeiyu.common.SerializationUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 解码器
 */
public class ObjDecoder extends ByteToMessageDecoder {

    private Logger logger = LoggerFactory.getLogger(ObjDecoder.class);

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4){
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        //读取指令
        byte command = in.readByte();
        Class<? extends Packet> clazz = Packet.get(command);
        logger.info("解码器ObjDecoder--,clazz:[ {} ]", clazz.getSimpleName());
        //指令占了一位，剔除掉
        byte[] data = new byte[dataLength - 1];
        in.readBytes(data);
        out.add(SerializationUtil.deserialize(data, clazz));
    }
}
